<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%String path = request.getContextPath();%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<%@ taglib prefix="sys" uri="/WEB-INF/tld/sys.tld" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>借款申请</title>
    <style type="text/css">
    </style>
    <jsp:include page="../../../import.jsp" flush="true"/>
</head>

<body class="iframeBody">
<div class="Wrapper">
    <div class="sqPanel" style="margin-bottom: 5px;">
        <div class="sqPanel_head" style="height:35px;">
            <table class="table_full">
                <tr>
                    <td><b>借款人 </b><span >${usrNm}/${usrMobile}</span></td>
                    <td><b>借款时间 </b><span >${loanDate}</span></td>
                    <td><b>所属机构 </b><span >${usrOrgCd}</span></td>
                    <td><b>借款金额合计 </b><span >${totalAmt}</span></td>
                </tr>
            </table>
        </div>
        <span onclick="addNewRow()" id="addNewRowBtn" class="sq-button sq-button-round">添加行</span>
        <span onclick="deleteRow()" id="deleteRowBtn" class="sq-button sq-button-round">删除选中行</span>


        <div class="sqPanel_body">
            <div id="ligergrid1" class="sq-grid"></div>
        </div>
        <div class="fieldBox col_100" id="up1">
			<div class="field">
				<jsp:include page="../finCommFilesUpload.jsp" flush="true" >
					<jsp:param name="filePath" value="ass"/>
				</jsp:include>
				<div id="fileUpload1" class="upfileBoxs"></div>
				<span class="sq-button sq-button-hasicon" id="btnUpload1" onclick="ajaxFileUploadImg('uploads1',1)">
					<i class="sqBtnIco_9"></i>上传
				</span>
			</div>
		</div>
		<div class="fieldBox col_100">
			<div style="width: 98%; margin-left: 1%;">
				<jsp:include page="../finCommFilesList.jsp" flush="true" ></jsp:include>
				<div id="ligergrid_file1" class="sq-grid"></div>
			</div>
		</div>
        
        
        <div class="sqPanel_head" style="height:35px;">
            <table class="table_full">
                <tr>
                    <td>
                        <span style="color:red">如果您调整了借款记录信息，请务必再次保存，确保重新生成付款信息！</span>
                        <span onclick="saveLoanDtl()" id="saveLoanDtlBtn" class="sq-button sq-button-round">保存借款信息</span>
                    </td>
                </tr>

            </table>
        </div>

    </div>
    <!-- 付款信息 -->
    <div class="sqPanel" id="dtlPanel" style="margin-bottom: 5px;">
        <div class="sqPanel_head" style="height:35px;">
            <table class="table_full">
                <tr>
                    <td><span >付款信息</span></td>

                </tr>
            </table>
        </div>

        <div class="sqPanel_body">
            <div id="dtlgrid" class="sq-grid"></div>
        </div>
        <div class="sqPanel_head" style="height:35px;">
            <table class="table_full">
                <tr>
                    <td>
                        <span onclick="saveApply(0)" id="tempSaveBtn" class="sq-button sq-button-round">暂存</span>
                        <span onclick="saveApply(1)" id="saveBtn" class="sq-button sq-button-round">确认并提交付款审批</span>
                        <span onclick="saveApply(2)" id="saveBtn2" class="sq-button sq-button-round">保存</span>
                    </td>
                </tr>

            </table>
        </div>

    </div>
</div>



<script type="text/javascript">
	var upload_result_params_u = [];

    var grid = null, form = null;
    var newFlag='${newFlag}';
    var loanInfoId = '${loanInfoId}';
    var applyInfoId = '${applyInfoId}';
    var loanTypList = eval('${finLoanTypList}');
    var payTypList = eval('${finPayTypList}');
    var isMust = '${isMust}';
    var payDtlEditable = '${payDtlEditable}';
    var showSaveApplyBtn = '${showSaveApplyBtn}'
    var isAccount = '${showSaveBtn}';
    var isNeedUpload = '${isNeedUpload}';
    $(function () {
    	//加载	
   	   loadFilesLiger(1, applyInfoId);//加载停车场文件列表信息
       initSaveBtn2();
        $("#dtlPanel").hide();
        var option = {
            columns: [
                {display: '借款金额', name: 'loanAmt', width: 200, align: 'left', enabledSort: false,editor:{type:'number'}},
                {display: '借款类型', name: 'loanTypCd', width: 140, align: 'left', enabledSort: false,editor:{type:'select',data: loanTypList, valueField: 'key', textField: 'value'},render:function(item){
                        for(var i =0 ; i< loanTypList.length;i++){
                            if(loanTypList[i].key == item.loanTypCd){
                                return loanTypList[i].value;
                            }
                        }
                    }},
                {display: '付款方式', name: 'payTypCd', width: 140, align: 'left', enabledSort: false,editor:{type:'select',data: payTypList, valueField: 'key', textField: 'value'},render:function(item){
                        for(var i =0 ; i< payTypList.length;i++){
                            if(payTypList[i].key == item.payTypCd){
                                return payTypList[i].value;
                            }
                        }
                    }},

                {
                    display: '备注', name: 'loanRem', minWidth: 240, align: 'left', enabledSort: false,editor:{type:'text'},
                    render: function (rowdata, rowindex, value){//鼠标移上去显示提示框
                        var h='<span class="gridTip" title="'+ value +'">'+ value +'</span>';
                        return h;
                    }
                },
            ],
            enabledEdit: true, checkbox:true,rownumbers:true,isScroll: false,root:'rows',
            onAfterShowData: function () {//备注显示提示框需要此部分代码
				$(".gridTip").grid_ligerTip();
			}
        };
        if(loanInfoId){
            var url = "<%=path%>/capital/finance/loan/apply/initLoanDtlList.do?loanInfoId="+loanInfoId;
            option.url=url;
            option.method="get";
        }
        if(isMust == 1){
            option.enabledEdit=false;
            hideButton();
        }

        if(showSaveApplyBtn =="0"){
            $("#tempSaveBtn").hide();
            $("#saveBtn").hide();
        }else{
            $("#tempSaveBtn").show();
            $("#saveBtn").show();
        }

        grid = $("#ligergrid1").ligerGrid(option);
        grid.setHeight(300);
        $("#pageloading").hide();

        if(applyInfoId){
            initPayDtl(applyInfoId)
        }else if(newFlag=="0"){ //二次借款
            // saveLoanDtl();
            initPayDtl(applyInfoId)
        }
    });
    function initSaveBtn2(){
        $("#saveBtn2").hide();
        if(isAccount=="1"){
            $("#saveBtn2").show();
        }
        if(isNeedUpload=="0"){
        	$("#up1").attr("style","display:none;");
        }
    }
    function hideButton(){
        $("#addNewRowBtn").hide();
        $("#deleteRowBtn").hide();

        $("#saveLoanDtlBtn").hide();
    }
    function addNewRow()
    {
        var row = grid.getSelectedRow();
        //参数1:rowdata(非必填)
        //参数2:插入的位置 Row Data
        //参数3:之前或者之后(非必填)
        grid.addRow({payTypCd:1});//默认外付网银
    }
    function deleteRow()
    {
        grid.deleteSelectedRow();
    }

    /**
     * 保存借款信息
     * 新增或者修改
     */
    function saveLoanDtl(){
    	var f_Grid2 = liger.get("ligergrid_file1")
        var data = grid.getData();
        var flag = validateLoanDtl(data);
        if(!flag){
            UIUtils.alertWarning("您有必填信息未填")
            return false;
        }
        var waiting = $.ligerDialog.waitting('正在执行中,请稍候...');
        // ajax
        var fileParams = getUploadResultParams(1);
        var url = "<%=path%>/capital/finance/loan/apply/saveOrUpdateLoanDtl.do?loanInfoId="+loanInfoId + "&applyInfoId="+applyInfoId + "&newFlag="+newFlag;
        var param = {data:JSON.stringify(data),fileParams:JSON.stringify(f_Grid2.getData())};
        $.get(url,param,function(res){
            res = JSON.parse(res)
            loanInfoId = res.loanInfoId;
            applyInfoId = res.payApplyId;
            // 加载pay dtl list
            initPayDtl(applyInfoId);
            waiting.close();
        })
        
    }
    /**
     * 非空校验
     */
    function validateLoanDtl(rows){
        for(var row of rows){
            if(!row.loanAmt){
                return false;
            }
            if(!row.loanTypCd){
                return false;
            }
            if(!row.payTypCd){
                return false;
            }

        }
        return true;
    }
    <%--function savePayDtLList() {--%>
        <%--var payDtlList = payDtlGrid.getData();--%>
        <%--var param = {payDtlList: JSON.stringify(payDtlList)};--%>
        <%--var url = "<%=path%>/capital/finance/loan/apply/savePayDtlList.do";--%>
        <%--$.get(url, param, function (res) {--%>

        <%--})--%>
    <%--}--%>
    /**
     * 保存申请信息
     * 暂存或发起流程
     */
    function saveApply(action){
        var payDtlList = payDtlGrid.getData();
        for(var dtl of payDtlList){
            dtl.payAmt = dtl.payAmt*100;
        }
        var url = "<%=path%>/capital/finance/loan/apply/save.do";
        var param = {payApplyId:applyInfoId,action:action,payDtlList:JSON.stringify(payDtlList)};
        $.get(url,param,function(res){
            res = JSON.parse(res);
            // TODO 这里可能会保存失败
            if(res.code=="200" ){
                UIUtils.alertSuccess(res.info);
                Remove_navTab()
            }else if(res.code=="202"){ //
                if(confirm(res.info)){
                    param.confirm=1;
                    $.get(url,param,function(a){
                        a = JSON.parse(a);
                        UIUtils.alertSuccess(res.info);
                        Remove_navTab()
                    });
                }
            }else if(res.code=="201" || res.code=="203" || res.code=="204" || res.code=="500"){
                UIUtils.alertError(res.info)
            }
        })
    }
    //格式化时间
    function renderDate(rowdata, index, value) {
        var dateStr = "";
        if (null != value) {
            var date = new Date(value);
            dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
        }
        return dateStr;
    }

    var payDtlGrid = null;
    /**
     * 加载paydtlgrid
     */
    function initPayDtl(applyInfoId){
        initPayDtlGrid(applyInfoId);
        $("#dtlPanel").show();
    }

    /**
     * 加载借款paydtlgrid
     * @param applyInfoId
     */
    function initPayDtlGrid(applyInfoId){
        var url = "<%=path%>/capital/finance/loan/apply/initPayDtlList.do?applyInfoId="+applyInfoId+ "&newFlag="+newFlag;
        var option = {
            url: url,
            method: 'get',
            columns: [
                {display: 'id', name: 'id', minWidth: 30, align: 'left',hide:true},
                {display: '借款金额', name: 'loanAmt', minWidth: 100, align: 'left'},
                {display: '借款类型', name: 'loanTypCd', width: 140, align: 'left'},
                {display: '付款方式', name: 'payTypCd', width: 140, align: 'left'},
                {display: '本次申请付款金额（元）', name: 'payAmt', width: 140, align: 'left',editor:{type:'number'}},
                {display: '收款账户', name: 'rcptUnt', width: 140, align: 'left'},
                {display: '收款账号', name: 'accNo', width: 140, align: 'left',render:function(rowdata){
                    if(rowdata.bkId){
                        return  '<a class="sq-button-hasicon" style="cursor: pointer;" onclick="toBankAccView(' + rowdata.bkId + ');">'+rowdata.accNo+'</a>  '
                    }
                }},
                {display: '开户行', name: 'payeeBkNm', width: 140, align: 'left'},
                {display: '操作', name: '', width: 240, align: 'left',render:function(rowdata){
                        var res = "";
                        res += '<a class="sq-button-hasicon" style="cursor: pointer;" onclick="toBankAccList(' + rowdata.id + ');"><i class="sqBtnIco_49"></i>添加收款方信息</a>  ' ;
                        res += '<a class="sq-button-hasicon" style="cursor: pointer;" onclick="toBindAssetPage(' + rowdata.id + ',' +rowdata.payAmt+ ');"><i class="sqBtnIco_49"></i>绑定资产(<span id="span'+rowdata.id+'">'+rowdata.assetCount+'</span>)</a>' ;
                        return res;
                    }},
            ],
            enabledEdit: true, checkbox:true,rownumbers:true,isScroll: false,root: 'rows',onEndEdit:validateAmt,

        };
        if(payDtlEditable=="0"){
            option.enabledEdit=false;
        }
        payDtlGrid = $("#dtlgrid").ligerGrid(option);
        payDtlGrid.setHeight(300);
        $("#pageloading").hide();
    }
    // 限制输入的金额
    function validateAmt(e){
        var record = e.record;
        if(e.column.name=="payAmt"){

            if(parseFloat(record.amtLeft)<parseFloat(record.payAmt)){
                UIUtils.alertError("申请金额不能大于剩余借款金额")
                return false;
            }
        }
    }
    function bindAssetCallBack(len,payDtlId){
        $("#span"+payDtlId).html(len);
    }

    function toBindAssetPage(payDtlId,payAmt){

        var btn2 = "${isAccount}";
        var url = '<%=path%>/capital/finance/loan/apply/asset/toBindList.do?payDtlId='+payDtlId+'&payAmt='+payAmt;
        if(btn2=="1"){ //不可编辑
            url += "&editAble=0";
        }
        parent.Add_navTab('tab_fiance_asset_'+payDtlId,'绑定资产',url,bindAssetCallBack);
    }
    function callback(payDtlId,rcptUnt,accNo,bkNm,bkId,bkNo){
        if(payDtlId){
            var rowIndex = null;
            var rowsData = payDtlGrid.data.rows;
            for(var i =0 ;i< rowsData.length;i++){
                var rowData = rowsData[i];
                if(payDtlId == rowData.id){
                    rowIndex = i;
                    break;
                }
            }
            if(rowIndex != null){
                var row = payDtlGrid.getRow(rowIndex);
                payDtlGrid.updateRow(row,{rcptUnt:rcptUnt,accNo:accNo,payeeBkNo:bkNo,bkId:bkId});
            }
        }
        // payDtlGrid.reload();
    }
    /**
     * 添加收款方信息
     * @param payDtlId
     */
    function toBankAccList(payDtlId){
        var bankAccEditable = "${bankAccEditable}";
        var btn1 = "${payDtlEditable}";
        var url = '<%=path%>/capital/finance/loan/apply/bankAcc/toListPage.do?payDtlId='+payDtlId;
        if(btn1 == "1" || bankAccEditable=="1"){
            url += '&editAble=1';
        }else{
            url += '&editAble=0';
        }
        parent.Add_navTab('tab_finace_bank_'+payDtlId,'添加收款方信息',url,callback);
    }
    /**
     * 查看银行卡页面
     * @param bkId
     */
    function toBankAccView(bkId){
        var url = '<%=path%>/capital/finance/loan/apply/bankAcc/view.do?bkId='+bkId;
        parent.Add_navTab('tab_finace_bank_acc_view_'+bkId,'查看银行卡信息',url);
    }
    
	//显示已上传但是未保存的文件列表
	function showFiles(data, index){
		var sysDate = $("#sysDate").val();
		var loginUsrNm = $("#loginUsrNm").val();
		var f_Grid = liger.get("ligergrid_file"+index);
		var uploadJOSN = data;
		for (var i=0; i< uploadJOSN.length; i++){ 
    		//添加行-追加行
    		f_Grid.addRow({fileNm: uploadJOSN[i].fileNm,filePath: serverPrefixPath+uploadJOSN[i].filePath, crtUsrRlNm: loginUsrNm, crtTm: sysDate, doSthFlag: "1", ligerIndex: index,absLocPath:uploadJOSN[i].absLocPath});
		}
	}
	
</script>

</body>
</html>
